<template>
  <div class="divBox">
    <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: 0 }">
      <div class="padding-add">
        <el-form inline size="small" label-position="right" @submit.native.prevent>
          <el-form-item label="作品标题：">
            <el-input
              v-model.trim="title"
              @keyup.enter.native="handerSearch()"
              placeholder="请输入作品标题"
              class="selWidth"
              size="small"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="作者：">
            <el-input
              v-model.trim="author"
              @keyup.enter.native="handerSearch()"
              placeholder="请输入作者"
              class="selWidth"
              size="small"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="类型：">
            <el-select
              v-model="listPram.type"
              clearable
              class="selWidth"
              placeholder="请选择类型"
              @change="handerSearch"
            >
              <el-option :value="1" label="图文"></el-option>
              <el-option :value="2" label="视频"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分类：">
            <el-select
              v-model="listPram.categoryId"
              clearable
              class="selWidth"
              placeholder="请选择分类"
              @change="handerSearch"
            >
              <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态：">
            <el-select
              v-model="listPram.auditStatus"
              clearable
              class="selWidth"
              placeholder="请选择审核状态"
              @change="handerSearch"
            >
              <el-option :value="0" label="待审核"></el-option>
              <el-option :value="1" label="审核通过"></el-option>
              <el-option :value="2" label="审核失败"></el-option>
              <el-option :value="3" label="平台关闭"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="handerSearch()">查询</el-button>
            <el-button size="small" @click="reset()">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="box-card mt14" :body-style="{ padding: '20px' }" shadow="never" :bordered="false">
      <el-button size="small" type="primary" class="mr10" @click="handleAdd">添加作品</el-button>
      <el-table v-loading="listLoading" :data="listData.list" size="small" highlight-current-row class="mt20">
        <el-table-column prop="id" label="作品ID" min-width="80" />
        <el-table-column prop="title" label="标题" min-width="160" :show-overflow-tooltip="true" />
        <el-table-column prop="authorName" label="作者昵称" min-width="120" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span v-if="scope.row.authorName">{{ scope.row.authorName }}</span>
            <span v-else class="no-author">无作者</span>
          </template>
        </el-table-column>
        <el-table-column prop="authorId" label="作者ID" min-width="80" />
        <el-table-column prop="type" label="作品类型" min-width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.type === 1 ? 'primary' : 'success'">
              {{ scope.row.type === 1 ? '图文' : '视频' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="封面" min-width="100">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.cover"
              :src="scope.row.cover"
              class="cover-image"
              :preview-src-list="[scope.row.cover]"
              fit="cover"
            />
            <span v-else class="no-cover">无封面</span>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="创意分类" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="话题" min-width="150" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="!scope.row.topicList || scope.row.topicList.length === 0">无话题</div>
            <div v-else>
              <el-tag
                v-for="(topic, index) in scope.row.topicList"
                :key="index"
                size="mini"
                class="topic-tag"
              >
                {{ topic }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="推荐" min-width="100">
          <template slot-scope="scope">
            <el-rate disabled v-model="scope.row.star" />
          </template>
        </el-table-column>
        <el-table-column label="审核状态" min-width="120">
          <template slot-scope="scope">
            <el-tag :type="getAuditStatusType(scope.row.auditStatus)">
              {{ getAuditStatusText(scope.row.auditStatus) }}
            </el-tag>
            <span v-if="scope.row.refusal" class="refusal-reason">拒绝理由: {{ scope.row.refusal }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="likeNum" label="点赞数" min-width="80" />
        <el-table-column prop="replyNum" label="评论数" min-width="80" />
        <el-table-column label="评论状态" min-width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.replyStatus === 1" type="success">开启</el-tag>
            <el-tag v-else-if="scope.row.replyStatus === 2" type="info">关闭</el-tag>
            <el-tag v-else-if="scope.row.replyStatus === 3" type="warning">平台关闭</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-dropdown @command="handleCommand" trigger="click">
              <span class="el-dropdown-link"> 更多<i class="el-icon-arrow-down el-icon--right"></i> </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{ action: 'detail', row: scope.row }">详情</el-dropdown-item>
                <el-dropdown-item :command="{ action: 'edit', row: scope.row }">修改</el-dropdown-item>
                <el-dropdown-item :command="{ action: 'delete', row: scope.row }">删除</el-dropdown-item>
                <el-dropdown-item :command="{ action: 'addComment', row: scope.row }">添加评论</el-dropdown-item>
                <el-dropdown-item :command="{ action: 'addLike', row: scope.row }">修改助力数</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-divider direction="vertical"></el-divider>
            <a @click="handleAudit(scope.row)" v-if="scope.row.auditStatus === 0">审核</a>
            <a @click="handleToggleComment(scope.row)" v-if="scope.row.auditStatus === 1">
              {{ scope.row.replyStatus === 1 ? '关闭评论' : '开启评论' }}
            </a>
            <a @click="handleForceDown(scope.row)" v-if="scope.row.auditStatus === 1">强制下架</a>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page="listPram.page"
        :page-sizes="constants.page.limit"
        :layout="constants.page.layout"
        :total="listData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加/编辑作品组件 - 页面层级显示 -->
    <div v-if="editDialogConfig.visible" class="edit-page-overlay">
      <div class="edit-page-container">
        <div class="edit-page-header">
          <h3>{{ editDialogConfig.isEdit === 0 ? '添加作品' : '编辑作品' }}</h3>
          <el-button type="text" @click="handlerHideDialog" class="close-btn">
            <i class="el-icon-close"></i>
          </el-button>
        </div>
        <div class="edit-page-content">
          <!-- 加载状态显示 -->
          <div v-if="editDialogConfig.editData && editDialogConfig.editData.loading" class="loading-container" v-loading="true" element-loading-text="正在加载数据..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
            <div style="height: 200px;"></div>
          </div>
          <!-- 编辑组件 -->
          <edit
            v-else
            :is-edit="editDialogConfig.isEdit"
            :edit-data="editDialogConfig.editData"
            @hideDialog="handlerHideDialog"
          />
        </div>
      </div>
    </div>


    <!-- 添加评论对话框 -->
    <el-dialog title="添加评论" :visible.sync="commentDialogVisible" width="600px">
      <el-form :model="commentForm" label-width="80px">
        <el-form-item label="选择用户：">
          <el-select
            v-model="commentForm.userId"
            placeholder="请选择用户"
            style="width: 100%"
            filterable
            clearable
            @change="onUserChange"
          >
            <el-option
              v-for="user in commentForm.userList"
              :key="user.euserId"
              :label="`${user.playerName} (ID: ${user.euserId})`"
              :value="user.euserId"
            >
              <span style="float: left">{{ user.playerName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">ID: {{ user.euserId }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评论内容：">
          <el-input
            v-model="commentForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入评论内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="commentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCommentSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 修改助力数对话框 -->
    <el-dialog title="虚拟助力数" :visible.sync="likeDialogVisible" width="500px">
      <div class="like-dialog-content">
        <div class="current-count">
          <span class="label">助力数：</span>
          <span class="value">{{ likeForm.currentCount }}</span>
        </div>
        
        <div class="modify-section">
          <div class="modify-label">修改助力数：</div>
          <el-radio-group v-model="likeForm.modifyType" @change="onLikeTypeChange">
            <el-radio label="add">增加</el-radio>
            <el-radio label="sub">减少</el-radio>
          </el-radio-group>
        </div>
        
        <div class="value-input-section">
          <span class="label">助力：</span>
          <el-input-number
            v-model="likeForm.modifyValue"
            :min="0"
            :max="1000"
            controls-position="right"
            @change="onLikeValueChange"
            class="like-input-number"
          />
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="likeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleLikeSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!--审核-->
    <el-drawer
      :visible.sync="dialogVisible"
      :direction="direction"
      custom-class="demo-drawer"
      size="1000px"
      ref="drawer"
      class="infoBox"
      @close="onClose"
    >
      <div v-loading="loading" v-if="dialogVisible">
        <div class="detailHead">
          <div class="acea-row row-between headerBox">
            <div class="full">
              <div class="order_icon"><span class="iconfont icon-shipinico"></span></div>
              <div class="text">
                <div class="title">{{ isExamine ? '内容审核' : '内容详情' }}</div>
                <div>
                  <span class="mr20"
                    >审核状态：<span class="color-warning">{{
                      formValidate.auditStatus | communityAuditStatusFilter
                    }}</span></span
                  >
                </div>
              </div>
            </div>
            <div v-if="isExamine" class="acea-row justify-content">
              <el-button
                v-debounceClick="
                  () => {
                    onAuditStatus(2);
                  }
                "
                style="margin-left: 0"
                >{{ loadingBtn ? '提交中 ...' : '审核拒绝' }}</el-button
              >
              <el-button
                type="primary"
                v-debounceClick="
                  () => {
                    onAuditStatus(1);
                  }
                "
                >{{ loadingBtn ? '提交中 ...' : '审核通过' }}</el-button
              >
            </div>
          </div>
        </div>
        <el-tabs type="border-card" v-model="currentTab">
          <!-- 商品信息-->
          <el-tab-pane label="基础信息" name="0">
            <div class="detailSection">
              <ul class="list mt-16">
                <li class="item">
                  <div class="tips">作品ID：</div>
                  <div class="value">
                    {{ formValidate.id }}
                  </div>
                </li>
                <li class="item">
                  <div class="tips">作品标题：</div>
                  <div class="value">
                    {{ formValidate.title | filterEmpty }}
                  </div>
                </li>
                <li class="item">
                  <div class="tips">作品类型：</div>
                  <div class="value">
                    <el-tag :type="formValidate.type === 1 ? 'primary' : 'success'">
                      {{ formValidate.type === 1 ? '图文' : '视频' }}
                    </el-tag>
                  </div>
                </li>
                <li class="item">
                  <div class="tips">作者昵称：</div>
                  <div class="value">
                    {{ formValidate.authorName | filterEmpty }}
                  </div>
                </li>
                <li class="item">
                  <div class="tips">作者ID：</div>
                  <div class="value">
                    {{ formValidate.euserId | filterEmpty }}
                  </div>
                </li>
                <li class="item">
                  <div class="tips">分类名称：</div>
                  <div class="value">
                    {{ formValidate.categoryName | filterEmpty }}
                  </div>
                </li>
                <li class="item">
                  <div class="tips">话题标签：</div>
                  <div class="value">
                    <el-tag 
                      v-for="(topic, index) in (formValidate.topicList || [])" 
                      :key="index" 
                      type="info" 
                      size="small" 
                      style="margin-right: 8px;"
                    >
                      {{ topic }}
                    </el-tag>
                    <span v-if="!formValidate.topicList || formValidate.topicList.length === 0" class="text-muted">无</span>
                  </div>
                </li>
                <li class="item">
                  <div class="tips">星级：</div>
                  <div class="value">
                    <el-rate 
                      v-model="formValidate.star" 
                      disabled 
                      show-score 
                      :max="5"
                      text-color="#ff9900"
                    />
                  </div>
                </li>
                <li class="item">
                  <div class="tips">设计过程：</div>
                  <div class="value">
                    <el-tag :type="getDesignProcessType(formValidate.designProcess)">
                      {{ getDesignProcessText(formValidate.designProcess) }}
                    </el-tag>
                  </div>
                </li>
                <li class="item">
                  <div class="tips">AI工具：</div>
                  <div class="value">
                    {{ formValidate.aitool | filterEmpty }}
                  </div>
                </li>
                <li class="item">
                  <div class="tips">播放器：</div>
                  <div class="value">
                    {{ formValidate.player | filterEmpty }}
                  </div>
                </li>
                <li class="item">
                  <div class="tips">社区类型：</div>
                  <div class="value">
                    <el-tag :type="formValidate.commType === '1' ? 'success' : 'info'">
                      {{ formValidate.commType === '1' ? '真实' : '虚拟' }}
                    </el-tag>
                  </div>
                </li>
                <li class="item">
                  <div class="tips">点赞数：</div>
                  <div class="value">
                    {{ formValidate.likeNum || 0 }}
                  </div>
                </li>
                <li class="item">
                  <div class="tips">评论数：</div>
                  <div class="value">
                    {{ formValidate.replyNum || 0 }}
                  </div>
                </li>
                <li class="item">
                  <div class="tips">分享数：</div>
                  <div class="value">
                    {{ formValidate.shareNum || 0 }}
                  </div>
                </li>
                <li class="item">
                  <div class="tips">浏览量：</div>
                  <div class="value">
                    {{ formValidate.views || 0 }}
                  </div>
                </li>
                <li class="item">
                  <div class="tips">创建时间：</div>
                  <div class="value">
                    {{ formValidate.createTime }}
                  </div>
                </li>
                <li class="item" v-if="formValidate.operateTime">
                  <div class="tips">操作时间：</div>
                  <div class="value">
                    {{ formValidate.operateTime }}
                  </div>
                </li>
              </ul>
              <div class="list" style="display: block">
                <div class="item">
                  <div class="tips">文章内容：</div>
                  <div class="value">
                    {{ formValidate.content | filterEmpty }}
                  </div>
                </div>
                <div class="item row-middle">
                  <div class="tips">封面图：</div>
                  <div class="upLoadPicBox">
                    <el-image
                      class="pictrue"
                      :src="formValidate.cover"
                      :preview-src-list="[formValidate.cover]"
                    ></el-image>
                  </div>
                </div>
                <div class="item" v-if="formValidate.type === 2 && formValidate.video">
                  <div class="acea-row row-middle">
                    <div class="tips">短视频：</div>
                    <div class="upLoadPicBox">
                      <video class="pictrue" :src="formValidate.video" controls="controls">
                        您的浏览器不支持 video 标签。
                      </video>
                    </div>
                  </div>
                </div>
                <div class="item" v-if="formValidate.type === 1 && formValidate.image">
                  <div class="tips">图片：</div>
                  <div
                    v-for="(item, index) in formValidate.image.split(',')"
                    :key="index"
                    class="pictrue"
                    style="display: inline-block; margin: 0 10px 10px 0"
                  >
                    <el-image class="pictrue" :src="item || ''" :preview-src-list="[item ? item : '']" />
                  </div>
                </div>
                <div class="item" v-if="formValidate.auditStatus === 2 || formValidate.auditStatus === 3">
                  <div class="tips">{{ formValidate.auditStatus === 2 ? '拒绝原因：' : '关闭原因：' }}</div>
                  <div class="value">
                    {{ formValidate.refusal }}
                  </div>
                </div>
                <div class="item" v-if="formValidate.operateTime">
                  <div class="tips">{{ formValidate.auditStatus === 3 ? '关闭时间：' : '审核时间：' }}</div>
                  <div class="value">
                    {{ formValidate.operateTime }}
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="关联商品" name="1">
            <el-table
              class="mt20"
              ref="tableList"
              row-key="id"
              :data="formValidate.productList"
              size="small"
              border
              style="width: 100%"
            >
              <el-table-column prop="id" label="ID" min-width="45" />
              <el-table-column min-width="180" label="商品信息">
                <template slot-scope="scope">
                  <div class="acea-row row-middle">
                    <div class="demo-image__preview mr10 acea-row">
                      <el-image :src="scope.row.productImage" :preview-src-list="[scope.row.productImage]" />
                    </div>
                    <div class="row_title line2">{{ scope.row.productName }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="售价" width="120" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="评论列表" name="2">
            <el-table
              ref="tableList"
              row-key="id"
              :data="replyData.data"
              size="small"
              border
              class="mt20"
              style="width: 100%"
              :default-expand-all="isExpandAll"
              :tree-props="{ children: 'replyList', hasChildren: 'hasChildren' }"
            >
              <el-table-column prop="用户名/Id" label="ID" min-width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.nickname + '/' + scope.row.id }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="content" label="评论内容" width="150" :show-overflow-tooltip="true" />
              <el-table-column prop="countReply" label="评论数" min-width="100" />
              <el-table-column prop="countStart" label="助力数" min-width="100" />
              <el-table-column label="评论时间" min-width="150" prop="createTime" />
              <el-table-column label="操作" width="120" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleReplyDelete(scope.row.id, scope.$index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div class="block">
              <el-pagination
                :page-sizes="[20, 40, 60, 80]"
                :page-size="tableFromReply.limit"
                :current-page="tableFromReply.page"
                layout="total, sizes, prev, pager, next, jumper"
                :total="replyData.total"
                @size-change="handleSizeChangeReply"
                @current-change="pageChangeReply"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="demo-drawer__footer">
        <div v-show="isExamine" class="from-foot-btn drawer_fix">
          <div class="acea-row justify-content"></div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
// +---------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +---------------------------------------------------------------------
// | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
// +---------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +---------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +---------------------------------------------------------------------
import edit from './edit';
import { fixImageUrl } from '@/utils/index.js'; // 图片URL协议处理
import request from '@/utils/request'; // HTTP请求
import { filterEmpty } from '@/filters';
import * as community from '@/api/community';

export default {
  components: { edit },
  data() {
    return {
      constants: this.$constants,
      listPram: {
        title: '',
        author: '',
        type: null,
        categoryId: null,
        auditStatus: null,
        commType: 2, // 添加commType=2参数
        page: 1,
        limit: this.$constants.page.limit[0],
      },
      title: '',
      author: '',
      listData: { list: [], total: 0 },
      editDialogConfig: {
        visible: false,
        editData: {},
        isEdit: 0, // 0=add 1=edit
      },
      listLoading: true,
      categoryList: [],
      topicList: [], // 标签列表
      currentRow: null,
      // 审核相关
      community_id: '',
      dialogVisible: false,
      isExamine: false,
      currentTab: 0,
      loading: false,
      loadingBtn: false,
      formValidate: {},
      // 审核表单
      auditStatusFrom: {
        auditStatus: 0,
        id: 0,
        refusalReason: '',
      },
      // 评论列表分页
      tableFromReply: {
        page: 1,
        limit: 20,
        nid: 0,
      },
      // 评论列表数据
      replyData: {
        data: [],
        total: 0,
      },
      // 是否展开，默认全部折叠
      isExpandAll: false,
      direction: 'rtl',
      // 评论对话框相关
      commentDialogVisible: false,
      currentCommentRow: null,
      commentForm: {
        content: '',
        userId: null,
        userList: []
      },
      // 助力数对话框相关
      likeDialogVisible: false,
      currentLikeRow: null,
      likeForm: {
        currentCount: 0,
        modifyType: 'add', // 'add' 或 'sub'
        modifyValue: 0
      },
      // 强制下架
      ruleForm: {
        id: 0,
        reason: '',
      },
    };
  },
  created() {
    this.handlerGetListData(this.listPram);
    this.getCategoryList();
    this.getTopicList();
  },
  methods: {
    filterEmpty,
    fixImageUrl,
    processImageUrl(url) {
      return this.fixImageUrl(url);
    },
    
    // 获取AI设计过程显示文本
    getDesignProcessText(designProcess) {
      switch (parseInt(designProcess)) {
        case 1:
          return '纯AI设计';
        case 2:
          return 'AI辅助设计';
        case 3:
          return '非AI设计';
        default:
          return '未知';
      }
    },
    
    // 获取AI设计过程标签类型
    getDesignProcessType(designProcess) {
      switch (parseInt(designProcess)) {
        case 1:
          return 'success'; // 纯AI设计 - 绿色
        case 2:
          return 'warning'; // AI辅助设计 - 橙色
        case 3:
          return 'info'; // 非AI设计 - 灰色
        default:
          return 'danger'; // 未知 - 红色
      }
    },
    // 获取分类列表
    getCategoryList() {
      community.communityCategoryListApi().then((res) => {
        // 只获取启用的分类数据
        this.categoryList = (res.list || []).filter(item => item.isShow === 1);
      }).catch((err) => {
        // 获取分类列表失败
        this.$message.error('获取分类列表失败');
      });
    },
    
    // 获取标签列表
    getTopicList() {
      community.communityTopicListApi({ page: 1, limit: 1000 }).then((res) => {
        this.topicList = res.list || []
      }).catch((err) => {
        // 获取标签列表失败
      })
    },
    
    // 根据标签ID获取标签名称
    getTopicName(topicId) {
      const topic = this.topicList.find(item => item.id == topicId)
      return topic ? topic.name : topicId
    },
    // 获取审核状态类型
    getAuditStatusType(status) {
      const statusMap = {
        0: 'warning', // 待审核
        1: 'success', // 审核通过
        2: 'danger', // 审核失败
        3: 'info', // 平台关闭
      };
      return statusMap[status] || 'info';
    },
    // 获取审核状态文本
    getAuditStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '审核通过',
        2: '审核失败',
        3: '平台关闭',
      };
      return statusMap[status] || '未知';
    },
    // 获取分类类型信息
    getCategoryType(categoryId) {
      const category = this.categoryList.find(item => item.id == categoryId);
      if (category) {
        return { 
          name: category.name, 
          type: category.id === 1 ? 'primary' : 'success' 
        };
      }
      return { name: '其他', type: 'info' };
    },
    // 搜索
    handerSearch() {
      this.listPram.page = 1;
      this.handlerGetListData(this.listPram);
    },
    // 获取列表数据
    handlerGetListData(pram) {
      this.listLoading = true;
      this.listPram.title = encodeURIComponent(this.title);
      this.listPram.author = encodeURIComponent(this.author);

      // 调用真实API
      request
        .get('/admin/platform/virtual/community/list', {
          params: {
            page: pram.page,
            limit: pram.limit,
            title: pram.title,
            author: pram.author,
            type: pram.type,
            categoryId: pram.categoryId,
            auditStatus: pram.auditStatus,
            commType: pram.commType,
          },
        })
        .then((res) => {
          this.listData = {
            list: res.list || [],
            total: res.total || 0,
          };
          this.listLoading = false;
        })
        .catch((err) => {
          // 获取作品列表失败
          this.$message.error('获取作品列表失败，请稍后重试');
          this.listData = { list: [], total: 0 };
          this.listLoading = false;
        });
    },
    // 添加作品
    handleAdd() {
      this.editDialogConfig.isEdit = 0;
      this.editDialogConfig.editData = {};
      this.editDialogConfig.visible = true;
    },
    // 处理操作命令
    handleCommand(command) {
      const { action, row } = command;
      this.currentRow = row;

      switch (action) {
        case 'detail':
          this.handleDetail(row);
          break;
        case 'edit':
          this.handleEdit(row);
          break;
        case 'delete':
          this.handleDelete(row);
          break;
        case 'addComment':
          this.handleAddComment(row);
          break;
        case 'addLike':
          this.handleAddLike(row);
          break;
      }
    },
    // 详情
    handleDetail(row) {
      this.editDialogConfig.isEdit = 2; // 2表示详情查看模式
      // 先显示loading状态
      this.editDialogConfig.editData = {
        id: row.id,
        loading: true // 添加loading标识
      };
      this.editDialogConfig.visible = true;
      // 调用详情接口获取完整数据
      this.getNoteDetail(row.id);
    },
    // 编辑
    handleEdit(row) {
      this.editDialogConfig.isEdit = 1; // 1表示编辑模式
      // 先显示loading状态
      this.editDialogConfig.editData = {
        id: row.id,
        loading: true // 添加loading标识
      };
      this.editDialogConfig.visible = true;
      // 调用详情接口获取完整数据用于编辑
      this.getNoteDetail(row.id);
    },
    // 删除
    handleDelete(row) {
      this.$modalSure('确定删除该作品吗？').then(() => {
        request
          .delete(`/admin/platform/virtual/community/delete/${row.id}`)
          .then((res) => {
            this.$message.success('删除成功');
            this.handlerGetListData(this.listPram);
          })
          .catch((err) => {
            // 删除作品失败
            this.$message.error('删除失败，请稍后重试');
          });
      });
    },
    // 添加评论
    handleAddComment(row) {
      this.currentCommentRow = row;
      this.commentDialogVisible = true;
      this.commentForm = {
        content: '',
        userId: row.euserId || null,
        userList: []
      };
      this.getUserList();
    },
    // 修改助力数
    handleAddLike(row) {
      this.currentLikeRow = row;
      this.likeDialogVisible = true;
      this.likeForm = {
        currentCount: row.likeNum || 0,
        modifyType: 'add', // 'add' 或 'sub'
        modifyValue: 0
      };
    },
    // 审核
    handleAudit(row) {
      this.community_id = row.id;
      this.dialogVisible = true;
      this.isExamine = true;
      this.currentTab = 0;
      this.getReplyNoteList(row.id);
      this.getNoteDetail(row.id);
    },
    // 切换评论状态
    handleToggleComment(row) {
      const isClosing = row.replyStatus !== 3;
      const confirmText = isClosing 
        ? '关闭评论吗？关闭之后该内容将无法评论' 
        : '取消强制关闭评论吗？取消后评论将变成用户关闭状态';
      
      this.$modalSure(confirmText).then(() => {
        request
          .post(`/admin/platform/community/note/reply/force/off/${row.id}`)
          .then((res) => {
            this.$message.success('操作成功');
            this.handlerGetListData(this.listPram);
          })
          .catch((err) => {
            // 切换评论状态失败
            this.$message.error('操作失败，请稍后重试');
          });
      });
    },
    // 强制下架
    handleForceDown(row) {
      this.$modalPrompt('textarea', '强制下架原因').then((V) => {
        this.ruleForm.reason = V;
        this.submit(row.id);
      });
    },
    submit(id) {
      this.ruleForm.id = id;
      community.communityNoteForcedDownApi(this.ruleForm).then((res) => {
        this.$message.success('下架成功');
        this.handlerGetListData(this.listPram);
      }).catch((err) => {
        // 强制下架失败
        this.$message.error('下架失败，请稍后重试');
      });
    },
    // 获取作品详情
    getNoteDetail(id) {
      this.loading = true;
      request
        .get(`/admin/platform/community/note/detail/${id}`, {
          params: {
            temp: Date.now() // 添加时间戳避免缓存
          }
        })
        .then((res) => {
          // 响应拦截器已经返回了 res.data，所以直接使用 res
          this.formValidate = res;
          
          // 如果是编辑模式或详情查看模式，需要将详情数据也设置到编辑表单中

          if (this.editDialogConfig.isEdit === 1 || this.editDialogConfig.isEdit === 2) {
            // 将详情接口返回的数据映射到编辑表单需要的字段
            // 先确定 replyStatus 的值，用于计算 forbidComment
            const replyStatus = res.replyStatus || res.reply_status || res.commentStatus || res.status || 2;

            const editData = {
              id: res.id,
              title: res.title,
              content: res.content, // 直接传递 content，让编辑组件的 watch 处理映射
              designType: res.designProcess ? res.designProcess.toString() : '3', // designProcess 映射到 designType
              replyStatus: replyStatus, // 添加原始的 replyStatus 字段
              forbidComment: (() => {
                // 转换逻辑：replyStatus(2,3) -> forbidComment(true)
                const result = replyStatus === 2 || replyStatus === 3;
                return result;
              })(),
              competitionType: res.categoryId ? res.categoryId.toString() : '1',
              topicIds: (() => {
                // 将 topicList 转换为 topicIds 字符串
                if (res.topicList && Array.isArray(res.topicList)) {
                  const ids = res.topicList.map(item => {
                    // 先检查item是否存在
                    if (!item) return null;

                    if (typeof item === 'object' && item.id) {
                      return item.id;
                    } else if (typeof item === 'string' || typeof item === 'number') {
                      return item;
                    }
                    return null;
                  }).filter(id => id !== null);

                  const result = ids.join(',');
                  return result;
                }

                return '';
              })(),
              aitool: res.aitool || '', // 直接传递 aitool 字符串，让编辑组件处理分割
              player: res.player || '', // 直接传递 player 字符串，让编辑组件处理分割
              virtualUserId: res.euserId || null,
              virtualUserName: res.authorName || '',
              cover: res.cover,
              image: res.image,
              video: res.video,
              type: res.type,
              authorName: res.authorName,
              euserId: res.euserId, // 添加 euserId 字段
              categoryName: res.categoryName, // 添加分类名称
              replyStatus: res.replyStatus || res.reply_status || res.commentStatus || res.status || 2, // 尝试多种可能的字段名
              topicList: res.topicList || res.tags || res.tagList || res.categoryTags || [], // 保留topicList用于显示
              topicIds: (() => {
                // 优先使用API返回的topicIds字段
                if (res.topicIds && res.topicIds !== '0') {
                  return res.topicIds;
                }

                // 如果没有topicIds，尝试从其他字段转换
                const tagData = res.topicList || res.tags || res.tagList || res.categoryTags || [];
                if (Array.isArray(tagData) && tagData.length > 0) {
                  const ids = tagData.map(item => {
                    // 先检查item是否存在
                    if (!item) return null;

                    if (typeof item === 'object' && item.id) {
                      return item.id;
                    } else if (typeof item === 'string' || typeof item === 'number') {
                      return item;
                    }
                    return null;
                  }).filter(id => id !== null);

                  const result = ids.join(',');
                  return result;
                }

                return '';
              })(),
              star: res.star || 0, // 添加星级
              likeNum: res.likeNum || 0, // 添加点赞数
              replyNum: res.replyNum || 0, // 添加评论数
              shareNum: res.shareNum || 0, // 添加分享数
              views: res.views || 0, // 添加浏览量
              auditStatus: res.auditStatus,
              refusal: res.refusal,
              operateTime: res.operateTime,
              createTime: res.createTime,
              commType: res.commType,
              productList: res.productList || [],
              designProcess: res.designProcess // 添加原始的设计过程字段
            };
            
            // 直接更新 editData 对象，确保响应式更新
            this.editDialogConfig.editData = {
              ...editData,
              loading: false // 数据加载完成，移除loading状态
            };
          }
          
          this.loading = false;
        })
        .catch((err) => {
          // 获取作品详情失败
          this.loading = false;
        });
    },
    // 获取评论列表
    getReplyNoteList(id) {
      this.tableFromReply.nid = id;
      request
        .get('/admin/platform/community/reply/note/list', {
          params: this.tableFromReply,
        })
        .then((res) => {
          this.replyData.total = res.total;
          this.replyData.data = res.list;
        })
        .catch((err) => {
          // 获取评论列表失败
        });
    },
    // 审核拒绝
    cancelForm() {
      this.$modalPrompt('textarea', '拒绝原因').then((V) => {
        this.auditStatusFrom.refusalReason = V;
        this.onAuditSubmit();
      });
    },
    // 审核点击
    onAuditStatus(type) {
      this.auditStatusFrom.auditStatus = type;
      if (type === 1) {
        this.$modalSure('审核通过该作品吗？').then(() => {
          this.onAuditSubmit();
        });
      } else {
        this.cancelForm();
      }
    },
    // 审核提交
    onAuditSubmit() {
      this.auditStatusFrom.id = this.community_id;
      this.loadingBtn = true;
      request
        .post('/admin/platform/community/note/audit', this.auditStatusFrom)
        .then((res) => {
          this.$message.success('操作成功');
          this.dialogVisible = false;
          this.loadingBtn = false;
          this.handlerGetListData(this.listPram);
        })
        .catch((err) => {
          // 审核失败
          this.loadingBtn = false;
        });
    },
    // 关闭审核对话框
    onClose() {
      this.dialogVisible = false;
    },
    // 评论分页
    pageChangeReply(page) {
      this.tableFromReply.page = page;
      this.getReplyNoteList(this.community_id);
    },
    handleSizeChangeReply(val) {
      this.tableFromReply.limit = val;
      this.getReplyNoteList(this.community_id);
    },
    // 删除评论
    handleReplyDelete(id) {
      this.$modalSure('删除该评论').then(() => {
        request
          .delete(`/admin/platform/community/reply/delete/${id}`)
          .then(() => {
            this.$message.success('删除成功');
            this.getReplyNoteList(this.community_id);
          })
          .catch((err) => {
            // 删除评论失败
          });
      });
    },
    // 隐藏对话框
    handlerHideDialog() {
      this.handlerGetListData(this.listPram);
      this.editDialogConfig.visible = false;
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.listPram.limit = val;
      this.handlerGetListData(this.listPram);
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.listPram.page = val;
      this.handlerGetListData(this.listPram);
    },
    // 获取用户列表
    getUserList() {
      request
        .get('/admin/platform/virtual/user/list', {
          params: {
            page: 1,
            limit: 100, // 获取前100个用户
            playerName: '',
            applyType: '-1'
          }
        })
        .then((res) => {
          this.commentForm.userList = res.list || [];
        })
        .catch((err) => {
          // 获取用户列表失败
          this.$message.error('获取用户列表失败');
        });
    },
    // 用户选择变化
    onUserChange(value) {
      this.commentForm.userId = value;
    },
    // 助力数修改类型变化
    onLikeTypeChange(type) {
      this.likeForm.modifyType = type;
    },
    // 助力数修改值变化
    onLikeValueChange(value) {
      this.likeForm.modifyValue = value;
    },
    // 提交助力数修改
    handleLikeSubmit() {
      if (this.likeForm.modifyValue <= 0) {
        this.$message.error('请输入有效的助力数量');
        return;
      }
      
      const requestData = {
        id: this.currentLikeRow.id,
        type: this.likeForm.modifyType,
        num: this.likeForm.modifyValue,
      };
      
      
      request
        .post('/admin/platform/community/reply/like/update', requestData)
        .then((res) => {
          this.$message.success('助力数修改成功');
          this.likeDialogVisible = false;
          this.handlerGetListData(this.listPram);
        })
        .catch((err) => {
          // 修改助力数失败
          this.$message.error('修改助力数失败，请稍后重试');
        });
    },
    // 提交评论
    handleCommentSubmit() {
      if (!this.commentForm.content.trim()) {
        this.$message.error('请输入评论内容');
        return;
      }
      if (!this.commentForm.userId) {
        this.$message.error('请选择用户');
        return;
      }
      
      const requestData = {
        noteId: this.currentCommentRow.id,
        replyId: 0,
        content: this.commentForm.content.trim(),
        euserId: this.commentForm.userId,
      };
      
      
      request
        .post('/admin/platform/community/reply/reply/add', requestData)
        .then((res) => {
          this.$message.success('评论添加成功');
          this.commentDialogVisible = false;
          this.handlerGetListData(this.listPram);
        })
        .catch((err) => {
          // 添加评论失败
          this.$message.error('评论添加失败，请稍后重试');
        });
    },
    // 重置
    reset() {
      this.author = '';
      this.title = '';
      this.listPram = {
        title: '',
        author: '',
        type: null,
        categoryId: null,
        auditStatus: null,
        commType: 2, // 重置时保持commType=2
        page: 1,
        limit: this.$constants.page.limit[0],
      };
      this.handlerGetListData(this.listPram);
    },
  },
};
</script>

<style scoped lang="scss">
.divBox {
  min-height: 100vh;
  position: relative;
  width: 100%;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}

/* 添加/编辑作品页面层级样式 - 限制在原页面区域内 */
.edit-page-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.edit-page-container {
  width: 100%;
  height: 100%;
  max-width: 100%;
  max-height: 100%;
  background: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;

  padding-left: 20px;
}

.edit-page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e6e6e6;
  background: #fafafa;
  flex-shrink: 0;

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 500;
    color: #333;
  }

  .close-btn {
    font-size: 20px;
    color: #999;
    padding: 0;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    background: none;
    cursor: pointer;

    &:hover {
      color: #666;
      background-color: #f5f5f5;
      border-radius: 4px;
    }
  }
}

.edit-page-content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
  width: 100%;
  height: 100%;
  margin-left: -20px;
  padding-left: 20px;
}

/* 审核对话框样式 */
.detailSection {
  border: none !important;
}

::v-deep .el-drawer__header {
  display: none;
}

.icon-shipinico {
  font-size: 50px;
}

.box-container {
  overflow: hidden;
}

.box-container .list {
  float: left;
  line-height: 40px;
}

.box-container .sp {
  width: 50%;
}

.box-container .sp3 {
  width: 33.3333%;
}

.box-container .sp100 {
  width: 100%;
}

.box-container .list .name {
  display: inline-block;
  width: 150px;
  text-align: right;
  color: #606266;
}

.box-container .list.image {
  margin-bottom: 40px;
}

.box-container .list.image img {
  position: relative;
  top: 40px;
}

::v-deep.el-form-item__content .el-rate {
  position: relative;
  top: 8px;
}

.selectStyle {
  width: 100%;
  padding-bottom: 20px;
}

::v-deep .el-image__preview {
  object-fit: contain;
}

.cover-image {
  width: 60px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}

.no-cover {
  color: #999;
  font-size: 12px;
}

.no-author {
  color: #999;
  font-size: 12px;
}

.topic-tag {
  margin-right: 4px;
  margin-bottom: 2px;
}

.refusal-reason {
  display: block;
  font-size: 12px;
  color: #f56c6c;
  margin-top: 4px;
}

/* 助力数对话框样式 */
.like-dialog-content {
  padding: 20px 0;
}

.current-count {
  margin-bottom: 25px;
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .label {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }
  
  .value {
    font-size: 20px;
    font-weight: bold;
    color: #000;
  }
}

.modify-section {
  margin-bottom: 25px;
  display: flex;
  align-items: center;
  
  .modify-label {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-right: 20px;
    white-space: nowrap;
  }
  
  .el-radio-group {
    .el-radio {
      margin-right: 30px;
      
      .el-radio__label {
        font-size: 14px;
        color: #606266;
        padding-left: 8px;
      }
      
      &.is-checked .el-radio__label {
        color: #409eff;
        font-weight: 500;
      }
    }
  }
}

.value-input-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  
  .label {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }
  
  .like-input-number {
    width: 180px;
    
    .el-input__inner {
      text-align: center;
      font-size: 16px;
      font-weight: 500;
    }
    
    .el-input-number__decrease,
    .el-input-number__increase {
      width: 32px;
      height: 32px;
      line-height: 30px;
    }
  }
}
</style>
